<template>
  <div class="create-order-container">
    <div class="page-header">
      <h2>创建新订单</h2>
    </div>

    <el-form :model="orderForm" label-width="120px" :rules="rules" ref="orderFormRef" class="order-form">
      <!-- 寄件人和收件人信息部分 -->
      <el-row :gutter="20">
        <!-- 左侧：寄件人信息 -->
        <el-col :span="12">
          <el-card class="form-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>寄件人信息</h3>
                <el-button v-if="addressBookList.length > 0" link type="primary" @click="showAddressBook('sender')">
                  从地址簿选择
                </el-button>
              </div>
            </template>
            
            <el-form-item label="寄件人姓名" prop="senderName">
              <el-input v-model="orderForm.senderName" placeholder="请输入寄件人姓名" />
            </el-form-item>
            
            <el-form-item label="寄件人电话" prop="senderPhone">
              <el-input v-model="orderForm.senderPhone" placeholder="请输入寄件人电话" />
            </el-form-item>
            
            <el-form-item label="寄件省市区" prop="senderRegion">
              <el-cascader
                v-model="orderForm.senderRegion"
                :options="regionOptions"
                placeholder="请选择省/市/区"
                @change="handleSenderRegionChange"
              />
            </el-form-item>
            
            <el-form-item label="详细地址" prop="senderAddress">
              <el-input v-model="orderForm.senderAddress" type="textarea" :rows="2" placeholder="请输入详细地址" />
            </el-form-item>
          </el-card>
        </el-col>
        
        <!-- 右侧：收件人信息 -->
        <el-col :span="12">
          <el-card class="form-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>收件人信息</h3>
                <el-button v-if="addressBookList.length > 0" link type="primary" @click="showAddressBook('recipient')">
                  从地址簿选择
                </el-button>
              </div>
            </template>
            
            <el-form-item label="收件人姓名" prop="recipientName">
              <el-input v-model="orderForm.recipientName" placeholder="请输入收件人姓名" />
            </el-form-item>
            
            <el-form-item label="收件人电话" prop="recipientPhone">
              <el-input v-model="orderForm.recipientPhone" placeholder="请输入收件人电话" />
            </el-form-item>
            
            <el-form-item label="收件省市区" prop="recipientRegion">
              <el-cascader
                v-model="orderForm.recipientRegion"
                :options="regionOptions"
                placeholder="请选择省/市/区"
                @change="handleRecipientRegionChange"
              />
            </el-form-item>
            
            <el-form-item label="详细地址" prop="recipientAddress">
              <el-input v-model="orderForm.recipientAddress" type="textarea" :rows="2" placeholder="请输入详细地址" />
            </el-form-item>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 物品信息与运费计算 -->
      <el-row :gutter="20">
        <!-- 物品信息 -->
        <el-col :span="12">
          <el-card class="form-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>物品信息</h3>
              </div>
            </template>
            
            <el-form-item label="物品类型" prop="itemType">
              <el-select v-model="orderForm.itemType" placeholder="请选择物品类型" style="width: 100%">
                <el-option label="文件" value="document" />
                <el-option label="服装" value="clothing" />
                <el-option label="电子产品" value="electronics" />
                <el-option label="生活用品" value="daily" />
                <el-option label="食品" value="food" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="重量(kg)" prop="weight">
              <el-input-number v-model="orderForm.weight" :min="0.1" :precision="1" :step="0.5" @change="calculateFreight" style="width: 100%" />
            </el-form-item>
            
            <el-form-item label="体积(cm³)" prop="volume">
              <div class="volume-inputs">
                <el-input-number v-model="orderForm.length" :min="1" :step="1" placeholder="长" @change="calculateVolume" />
                <span class="multiply-sign">×</span>
                <el-input-number v-model="orderForm.width" :min="1" :step="1" placeholder="宽" @change="calculateVolume" />
                <span class="multiply-sign">×</span>
                <el-input-number v-model="orderForm.height" :min="1" :step="1" placeholder="高" @change="calculateVolume" />
              </div>
              <div class="volume-result">
                体积: {{ orderForm.volume }} cm³
                <el-tooltip content="体积重 = 体积(cm³) / 6000">
                  <span>, 体积重: {{ (orderForm.volume / 6000).toFixed(2) }} kg</span>
                </el-tooltip>
              </div>
            </el-form-item>
            
            <el-form-item label="保价金额(元)" prop="declaredValue">
              <el-input-number v-model="orderForm.declaredValue" :min="0" :step="100" style="width: 100%" @change="calculateFreight" />
            </el-form-item>
            
            <el-form-item label="备注" prop="remark">
              <el-input v-model="orderForm.remark" type="textarea" :rows="2" placeholder="可输入特殊要求或注意事项" />
            </el-form-item>
          </el-card>
        </el-col>
        
        <!-- 运费计算 -->
        <el-col :span="12">
          <el-card class="form-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>运费信息</h3>
              </div>
            </template>
            
            <div v-if="showDistanceInfo" class="distance-info">
              <div class="info-item">
                <span class="label">寄收地址：</span>
                <span>{{ getFullSenderAddress() }} → {{ getFullRecipientAddress() }}</span>
              </div>
              <div class="info-item">
                <span class="label">距离估算：</span>
                <span>{{ estimatedDistance }} 公里</span>
              </div>
            </div>
            
            <el-form-item label="服务类型" prop="serviceType">
              <el-radio-group v-model="orderForm.serviceType" @change="calculateFreight">
                <el-radio label="standard">标准快递</el-radio>
                <el-radio label="express">特快服务</el-radio>
                <el-radio label="economy">经济服务</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="增值服务" prop="additionalServices">
              <el-checkbox-group v-model="orderForm.additionalServices" @change="calculateFreight">
                <el-checkbox label="signatureRequired">签名确认</el-checkbox>
                <el-checkbox label="smsNotification">短信通知</el-checkbox>
                <el-checkbox label="priorityHandling">优先处理</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <div class="freight-breakdown">
              <div class="breakdown-title">运费明细</div>
              <div class="breakdown-item">
                <span>基础运费</span>
                <span>¥{{ baseFreight.toFixed(2) }}</span>
              </div>
              <div class="breakdown-item">
                <span>重量附加费</span>
                <span>¥{{ weightSurcharge.toFixed(2) }}</span>
              </div>
              <div class="breakdown-item">
                <span>保价费</span>
                <span>¥{{ insuranceFee.toFixed(2) }}</span>
              </div>
              <div class="breakdown-item">
                <span>服务附加费</span>
                <span>¥{{ serviceSurcharge.toFixed(2) }}</span>
              </div>
              <div class="breakdown-item total">
                <span>合计</span>
                <span>¥{{ orderForm.freight.toFixed(2) }}</span>
              </div>
            </div>

            <el-form-item label="支付方式" prop="paymentMethod">
              <el-radio-group v-model="orderForm.paymentMethod">
                <el-radio label="online">在线支付</el-radio>
                <el-radio label="cod">货到付款</el-radio>
                <el-radio label="monthly">月结账户</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-card>
        </el-col>
      </el-row>
      
      <div class="form-actions">
        <el-button type="primary" @click="submitOrder">创建订单</el-button>
        <el-button @click="resetForm">重置表单</el-button>
      </div>
    </el-form>
    
    <!-- 地址簿选择对话框 -->
    <el-dialog v-model="addressBookVisible" title="地址簿" width="500px">
      <el-table :data="addressBookList" style="width: 100%" height="300" highlight-current-row @row-click="selectAddress">
        <el-table-column prop="name" label="姓名" min-width="80" />
        <el-table-column prop="phone" label="电话" min-width="120" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressBookVisible = false">取消</el-button>
          <el-button type="primary" @click="addressBookVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'

const orderFormRef = ref<FormInstance>()

// 订单表单数据
const orderForm = reactive({
  // 寄件人信息
  senderName: '',
  senderPhone: '',
  senderRegion: [] as string[],
  senderAddress: '',
  
  // 收件人信息
  recipientName: '',
  recipientPhone: '',
  recipientRegion: [] as string[],
  recipientAddress: '',
  
  // 物品信息
  itemType: '',
  weight: 1.0,
  length: 0,
  width: 0,
  height: 0,
  volume: 0,
  declaredValue: 0,
  remark: '',
  
  // 运费信息
  serviceType: 'standard',
  additionalServices: [] as string[],
  freight: 0,
  paymentMethod: 'online'
})

// 表单验证规则
const rules = {
  senderName: [{ required: true, message: '请输入寄件人姓名', trigger: 'blur' }],
  senderPhone: [
    { required: true, message: '请输入寄件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  senderRegion: [{ required: true, message: '请选择寄件省市区', trigger: 'change' }],
  senderAddress: [{ required: true, message: '请输入寄件详细地址', trigger: 'blur' }],
  
  recipientName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  recipientPhone: [
    { required: true, message: '请输入收件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  recipientRegion: [{ required: true, message: '请选择收件省市区', trigger: 'change' }],
  recipientAddress: [{ required: true, message: '请输入收件详细地址', trigger: 'blur' }],
  
  itemType: [{ required: true, message: '请选择物品类型', trigger: 'change' }],
  weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
  serviceType: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
}

// 省市区数据（示例数据，实际项目中通常从API获取）
const regionOptions = [
  {
    value: '北京',
    label: '北京',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '朝阳区', label: '朝阳区' },
          { value: '海淀区', label: '海淀区' },
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' }
        ]
      }
    ]
  },
  {
    value: '上海',
    label: '上海',
    children: [
      {
        value: '上海市',
        label: '上海市',
        children: [
          { value: '浦东新区', label: '浦东新区' },
          { value: '黄浦区', label: '黄浦区' },
          { value: '徐汇区', label: '徐汇区' },
          { value: '长宁区', label: '长宁区' }
        ]
      }
    ]
  },
  {
    value: '广东',
    label: '广东',
    children: [
      {
        value: '广州市',
        label: '广州市',
        children: [
          { value: '天河区', label: '天河区' },
          { value: '海珠区', label: '海珠区' },
          { value: '越秀区', label: '越秀区' }
        ]
      },
      {
        value: '深圳市',
        label: '深圳市',
        children: [
          { value: '南山区', label: '南山区' },
          { value: '福田区', label: '福田区' },
          { value: '罗湖区', label: '罗湖区' }
        ]
      }
    ]
  }
]

// 地址簿相关
const addressBookVisible = ref(false)
const currentAddressType = ref('')
const addressBookList = [
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    region: ['北京', '北京市', '朝阳区'],
    address: '北京市朝阳区建国路88号'
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139002',
    region: ['上海', '上海市', '浦东新区'],
    address: '上海市浦东新区张江高科技园区'
  },
  {
    id: 3,
    name: '王五',
    phone: '13700137003',
    region: ['广东', '广州市', '天河区'],
    address: '广州市天河区天河路385号'
  }
]

// 运费计算相关变量
const baseFreight = ref(0)
const weightSurcharge = ref(0)
const insuranceFee = ref(0)
const serviceSurcharge = ref(0)
const estimatedDistance = ref(0)

// 显示地址簿
const showAddressBook = (type: string) => {
  currentAddressType.value = type
  addressBookVisible.value = true
}

// 选择地址
const selectAddress = (row: any) => {
  if (currentAddressType.value === 'sender') {
    orderForm.senderName = row.name
    orderForm.senderPhone = row.phone
    orderForm.senderRegion = row.region
    orderForm.senderAddress = row.address
  } else if (currentAddressType.value === 'recipient') {
    orderForm.recipientName = row.name
    orderForm.recipientPhone = row.phone
    orderForm.recipientRegion = row.region
    orderForm.recipientAddress = row.address
  }
  addressBookVisible.value = false
  calculateFreight()
}

// 计算体积
const calculateVolume = () => {
  if (orderForm.length && orderForm.width && orderForm.height) {
    orderForm.volume = orderForm.length * orderForm.width * orderForm.height
  } else {
    orderForm.volume = 0
  }
  calculateFreight()
}

// 获取完整寄件地址
const getFullSenderAddress = () => {
  if (orderForm.senderRegion && orderForm.senderRegion.length === 3) {
    return `${orderForm.senderRegion[0]}${orderForm.senderRegion[1]}${orderForm.senderRegion[2]}`
  }
  return ''
}

// 获取完整收件地址
const getFullRecipientAddress = () => {
  if (orderForm.recipientRegion && orderForm.recipientRegion.length === 3) {
    return `${orderForm.recipientRegion[0]}${orderForm.recipientRegion[1]}${orderForm.recipientRegion[2]}`
  }
  return ''
}

// 是否显示距离信息
const showDistanceInfo = computed(() => {
  return orderForm.senderRegion.length === 3 && orderForm.recipientRegion.length === 3
})

// 寄件地址变更处理
const handleSenderRegionChange = () => {
  calculateDistance()
  calculateFreight()
}

// 收件地址变更处理
const handleRecipientRegionChange = () => {
  calculateDistance()
  calculateFreight()
}

// 计算距离（简化版，实际应调用地图API）
const calculateDistance = () => {
  if (!showDistanceInfo.value) return
  
  // 模拟计算距离，实际项目中应调用地图API
  const senderProvince = orderForm.senderRegion[0]
  const recipientProvince = orderForm.recipientRegion[0]
  
  if (senderProvince === recipientProvince) {
    const senderCity = orderForm.senderRegion[1]
    const recipientCity = orderForm.recipientRegion[1]
    
    if (senderCity === recipientCity) {
      // 同城同区估算10-30公里
      estimatedDistance.value = Math.floor(Math.random() * 20) + 10
    } else {
      // 同省不同城估算50-300公里
      estimatedDistance.value = Math.floor(Math.random() * 250) + 50
    }
  } else {
    // 不同省估算300-2000公里
    estimatedDistance.value = Math.floor(Math.random() * 1700) + 300
  }
}

// 计算运费
const calculateFreight = () => {
  // 只有当两个地址都完整时才计算
  if (!showDistanceInfo.value) {
    orderForm.freight = 0
    return
  }
  
  // 计算基础运费 (基于距离)
  let baseFee = 0
  if (estimatedDistance.value <= 30) {
    // 同城基础费
    baseFee = 10
  } else if (estimatedDistance.value <= 300) {
    // 省内跨城费用
    baseFee = 15 + (estimatedDistance.value - 30) * 0.1
  } else {
    // 跨省费用
    baseFee = 42 + (estimatedDistance.value - 300) * 0.08
  }
  baseFreight.value = baseFee
  
  // 根据服务类型调整基础运费
  switch (orderForm.serviceType) {
    case 'express':
      baseFreight.value *= 1.5  // 特快服务加价50%
      break
    case 'economy':
      baseFreight.value *= 0.8  // 经济服务打八折
      break
  }
  
  // 计算重量附加费
  const weightLimit = 1  // 1kg以内不加收重量费
  const volumeWeight = orderForm.volume / 6000  // 体积重
  const chargeableWeight = Math.max(orderForm.weight, volumeWeight)  // 取实际重量和体积重中较大的一个
  
  if (chargeableWeight > weightLimit) {
    switch (orderForm.serviceType) {
      case 'express':
        weightSurcharge.value = (chargeableWeight - weightLimit) * 10  // 特快每超1kg加10元
        break
      case 'standard':
        weightSurcharge.value = (chargeableWeight - weightLimit) * 6  // 标准每超1kg加6元
        break
      case 'economy':
        weightSurcharge.value = (chargeableWeight - weightLimit) * 4  // 经济每超1kg加4元
        break
    }
  } else {
    weightSurcharge.value = 0
  }
  
  // 计算保价费
  if (orderForm.declaredValue > 0) {
    insuranceFee.value = Math.ceil(orderForm.declaredValue / 1000) * 3  // 每1000元收3元保价费
  } else {
    insuranceFee.value = 0
  }
  
  // 计算增值服务费
  serviceSurcharge.value = 0
  if (orderForm.additionalServices.includes('signatureRequired')) {
    serviceSurcharge.value += 5  // 签名确认服务5元
  }
  if (orderForm.additionalServices.includes('smsNotification')) {
    serviceSurcharge.value += 3  // 短信通知服务3元
  }
  if (orderForm.additionalServices.includes('priorityHandling')) {
    serviceSurcharge.value += 10  // 优先处理服务10元
  }
  
  // 计算总运费
  orderForm.freight = baseFreight.value + weightSurcharge.value + insuranceFee.value + serviceSurcharge.value
}

// 提交订单
const submitOrder = async () => {
  if (!orderFormRef.value) return
  
  await orderFormRef.value.validate((valid, fields) => {
    if (valid) {
      // 模拟订单提交
      setTimeout(() => {
        ElMessage.success('订单创建成功，订单号：LG' + new Date().getTime().toString().slice(0, 10))
        resetForm()
      }, 1000)
    } else {
      console.log('验证未通过:', fields)
      ElMessage.error('请完善必填信息')
    }
  })
}

// 重置表单
const resetForm = () => {
  if (orderFormRef.value) {
    orderFormRef.value.resetFields()
    orderForm.length = 0
    orderForm.width = 0
    orderForm.height = 0
    orderForm.volume = 0
    calculateFreight()
  }
}

onMounted(() => {
  // 页面加载时计算一次运费
  calculateFreight()
})
</script>

<style scoped>
.create-order-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.order-form {
  margin-bottom: 40px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.volume-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}

.multiply-sign {
  color: #909399;
}

.volume-result {
  margin-top: 8px;
  font-size: 13px;
  color: #606266;
}

.distance-info {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 16px;
}

.info-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  color: #909399;
  margin-right: 8px;
}

.freight-breakdown {
  margin: 20px 0;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.breakdown-title {
  background-color: #f5f7fa;
  padding: 10px 16px;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

.breakdown-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 16px;
  border-bottom: 1px solid #ebeef5;
}

.breakdown-item:last-child {
  border-bottom: none;
}

.breakdown-item.total {
  background-color: #fdf6ec;
  font-weight: 600;
  color: #e6a23c;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .order-form :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 8px;
  }
  
  .order-form :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style> 